<template>
  <el-page-header @back="goBack" style="margin: 20px 50px">
    <template #title>
      <div class="flex items-center">
        <span class="text-large font-600 mr-3"> 购物车 </span>
        <el-tag>请核实好您的购买清单后进行结算</el-tag>
      </div>
    </template>
    <template #content>
      <div class="flex items-center">
        <el-select v-model="selectedAddress" placeholder="选择地址">
          <el-option
            v-for="address in addressData"
            :key="address.id"
            :label="address.label"
            :value="
              address.street +
              address.detail +
              ' ' +
              address.zipCode +
              ' ' +
              address.recipient +
              ' ' +
              address.rePhone
            "
          ></el-option>
        </el-select>
      </div>
    </template>
    <template #extra>
      <div class="flex items-center">
        <el-button type="info" disabled>总计金额: {{ totalPrice }}</el-button>
        <el-button type="primary" class="ml-2" @click="checkout"
          >结算</el-button
        >
      </div>
    </template>
  </el-page-header>
  <el-container style="margin: 0 50px">
    <el-main style="display: flex; flex-direction: row; flex-wrap: wrap">
      <div
        class="cart-card-group"
        v-for="(item, index) in cartItems"
        :key="index"
      >
        <el-card class="cart-card">
          <div class="cart-card-image">
            <img
              :src="$apiImg + item.image"
              alt="商品图片"
              style="width: 100%; height: 300px; object-fit: cover"
            />
          </div>
          <div class="cart-card-info">
            <h3>{{ item.name }}</h3>
            <p>
              <span>价格：</span><span>{{ item.price }}</span>
            </p>
            <p>
              <span
                >数量：
                <el-input-number
                  v-model="item.quantity"
                  :min="1"
                  :max="10"
                  @change="handleChange(item.id, item.quantity)"
                />
              </span>
            </p>
          </div>
          <div class="cart-card-actions">
            <el-button type="danger" @click="removeFromCart(item.id)"
              >移除</el-button
            >
          </div>
        </el-card>
      </div>
    </el-main>
  </el-container>
</template>
<script>
import { reactive, toRefs, ref, computed } from 'vue'
import { cartGetApi, cartaddApi, delCartApi } from '@/api/shoppingCart'
import { detailApi } from '@/api/list'
import { userApi, getAdrApi } from '@/api/user'
import { orderAddApi } from '@/api/order'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'

export default {
  components: {},
  setup() {
    const data = reactive({
      cartItems: [],
      userInfo: {
        username: '',
        user_id: ''
      },
      addressData: [],
      selectedAddress: ''
    })

    const totalPrice = computed(() => {
      const total = data.cartItems.reduce(
        (total, item) => total + item.price * item.quantity,
        0
      )
      return total.toFixed(2)
    })

    const Addressfind = () => {
      getAdrApi({ username: store.state.uInfo.userInfo.username }).then(
        (res) => {
          if (res) {
            data.addressData = res.data
          }
        }
      )
    }

    const store = useStore()
    userApi({ username: store.state.uInfo.userInfo.username }).then((res) => {
      data.userInfo.user_id = res.data.id
    })
    const checkout = () => {
      if (data.cartItems.length == 0 || data.selectedAddress == '') {
        ElMessage({
          message: '没有数据或未选择收货地址',
          type: 'error',
          duration: 2000
        })
      } else {
        const checkoutData = {
          items: data.cartItems.map((item) => ({
            product_id: item.id, // 商品ID
            quantity: item.quantity, // 商品数量
            user_id: data.userInfo.user_id, // 用户ID
            address: data.selectedAddress
          }))
        }
        checkoutData.items.forEach((v) => {
          orderAddApi(v).then((res) => {
            if (res) {
              removeFromCart(v.product_id)
            }
          })
        })
      }
    }
    const activeIndex = ref('3')

    const cartListGet = () => {
      cartGetApi({ username: store.state.uInfo.userInfo.username })
        .then((res) => {
          if (res) {
            const productEntries = Object.entries(res.data)
            const detailPromises = productEntries.map(([key, quantity]) => {
              return detailApi({ key: key }).then((detail) => ({
                detail: detail.data,
                quantity: quantity
              }))
            })

            return Promise.all(detailPromises)
          }
        })
        .then((productDetailsWithQuantity) => {
          if (productDetailsWithQuantity) {
            const accumulatedDetails = []
            productDetailsWithQuantity.forEach((item) => {
              if (item && item.detail) {
                accumulatedDetails.push({
                  ...item.detail,
                  quantity: item.quantity
                })
              }
            })
            data.cartItems = accumulatedDetails
          }
        })
    }
    const handleChange = (productId, value) => {
      cartaddApi({
        productId: productId,
        username: store.state.uInfo.userInfo.username,
        quantity: value
      }).then((res) => {
        if (res) {
          const updatedCartItems = data.cartItems.map((item) => {
            if (item.productId === productId) {
              return { ...item, quantity: value }
            } else {
              return item
            }
          })
          data.cartItems = updatedCartItems
        }
      })
    }
    const removeFromCart = (itemId) => {
      delCartApi({
        productId: itemId,
        username: store.state.uInfo.userInfo.username
      }).then((res) => {
        if (res) {
          cartListGet()
        }
      })
    }

    const goBack = () => {
      window.history.back()
    }
    Addressfind()
    cartListGet()
    return {
      ...toRefs(data),
      activeIndex,
      goBack,
      checkout,
      totalPrice,
      handleChange,
      removeFromCart
    }
  },

  methods: {}
}
</script>
<style scoped>
.cart-card-group {
  flex: 0 0 calc(33.33% - 10px); /* 减少10px作为卡片之间的缝隙 */

  max-width: calc(33.33% - 10px); /* 减少10px作为卡片之间的缝隙 */

  margin-right: 10px; /* 增加卡片右边的缝隙 */

  margin-bottom: 10px;
}

/* 最后一个卡片不需要右边的缝隙 */

.cart-card-group:last-child {
  margin-right: 0;
}
</style>
